/*
Copyright [2020] [https://www.stylefeng.cn]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Guns采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点，可申请商业授权，获取Guns商业授权许可，请在官网购买授权，地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.sys.modular.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.enums.CommonStatusEnum;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.exception.PermissionException;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.exception.enums.PermissionExceptionEnum;
import cn.stylefeng.guns.core.exception.enums.StatusExceptionEnum;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.base.entity.BaseEntity;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.sys.core.enums.AdminTypeEnum;
import cn.stylefeng.guns.sys.core.enums.DataScopeTypeEnum;
import cn.stylefeng.guns.sys.core.mybatis.fieldfill.CustomMetaObjectHandler;
import cn.stylefeng.guns.sys.modular.dict.service.SysDictDataService;
import cn.stylefeng.guns.sys.modular.dict.service.SysDictTypeService;
import cn.stylefeng.guns.sys.modular.emp.service.SysEmpService;
import cn.stylefeng.guns.sys.modular.menu.mapper.SysMenuMapper;
import cn.stylefeng.guns.sys.modular.org.entity.SysOrg;
import cn.stylefeng.guns.sys.modular.org.service.SysOrgService;
import cn.stylefeng.guns.sys.modular.role.RoleConstant;
import cn.stylefeng.guns.sys.modular.role.entity.SysRole;
import cn.stylefeng.guns.sys.modular.role.param.SysRoleParam;
import cn.stylefeng.guns.sys.modular.role.service.SysRoleMenuService;
import cn.stylefeng.guns.sys.modular.role.service.SysRoleService;
import cn.stylefeng.guns.sys.modular.syssite.service.SysSiteAdminService;
import cn.stylefeng.guns.sys.modular.user.constant.ApiPayConstant;
import cn.stylefeng.guns.sys.modular.user.controller.dto.GetHuifuMsgDTO;
import cn.stylefeng.guns.sys.modular.user.controller.vo.EnterpriseUserMsgVO;
import cn.stylefeng.guns.sys.modular.user.controller.vo.GetHuifuMsgVO;
import cn.stylefeng.guns.sys.modular.user.controller.vo.SettleOrUpdateCommissionVO;
import cn.stylefeng.guns.sys.modular.user.controller.vo.UserBusinessSettleMsgVO;
import cn.stylefeng.guns.sys.modular.user.entity.*;
import cn.stylefeng.guns.sys.modular.user.factory.MD5Ry;
import cn.stylefeng.guns.sys.modular.user.mapper.*;
import cn.stylefeng.guns.sys.modular.user.param.SysTenantAddParam;
import cn.stylefeng.guns.sys.modular.user.param.SysTenantEditParam;
import cn.stylefeng.guns.sys.modular.user.param.SysTenantParam;
import cn.stylefeng.guns.sys.modular.user.service.SysTenantAsynDataService;
import cn.stylefeng.guns.sys.modular.user.service.SysTenantService;
import cn.stylefeng.guns.sys.modular.user.service.SysUserRoleService;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import cn.stylefeng.guns.sys.modular.user.utils.ApiPayUtil;
import cn.stylefeng.guns.sys.modular.user.utils.param.EnterpriseUserParam;
import cn.stylefeng.guns.sys.modular.user.utils.param.SettleInParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xuyuxiang
 * @date 2020/3/13 15:49
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDictTypeService dictTypeService;

    @Autowired
    private SysDictDataService dictDataService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysSiteAdminService sysSiteAdminService;

    @Autowired
    private EnterpriseUserMsgMapper enterpriseUserMsgMapper;

    @Autowired
    private UserBusinessSettleMsgMapper userBusinessSettleMsgMapper;

    @Autowired
    private ProvincialAndUrbanCodeMapper provincialAndUrbanCodeMapper;

    @Autowired
    private BankCodeMapper bankCodeMapper;

    @Autowired
    private DocumentTypeCodeMapper documentTypeCodeMapper;

    @Autowired
    private SysTenantAsynDataService sysTenantAsynDataService;


    @Override
    public PageResult<SysTenant> page(SysTenantParam sysTenantParam) {
        try {
            if (LoginContextHolder.me().isSuperAdmin()) {
                QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .ne(SysTenant::getStatus, CommonStatusEnum.DELETED.getCode())
                        .eq(sysTenantParam.getStatus() != null, SysTenant::getStatus, sysTenantParam.getStatus())
                        .like(StrUtil.isNotBlank(sysTenantParam.getContactMobile()), SysTenant::getContactMobile, sysTenantParam.getContactMobile())
                        .like(StrUtil.isNotBlank(sysTenantParam.getContactName()), SysTenant::getContactName, sysTenantParam.getContactName())
                        .like(StrUtil.isNotBlank(sysTenantParam.getName()), SysTenant::getName, sysTenantParam.getName())
                        .between(sysTenantParam.getExpireTimeBegin() != null && sysTenantParam.getExpireTimeEnd() != null,
                                SysTenant::getExpireTime, sysTenantParam.getExpireTimeBegin(), sysTenantParam.getExpireTimeEnd())
                        .orderByDesc(BaseEntity::getCreateTime);

                Page<SysTenant> sysTenantPage = baseMapper.selectPage(PageFactory.defaultPage(), queryWrapper);
                sysTenantPage.getRecords().stream().forEach(x -> {
                    //修改账号和密码
                    Long tenantAdminId = sysRoleService.getRoleIdByNameAndTenantId(RoleConstant.tenant_admin, x.getId());
                    SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, tenantAdminId)
                            .eq(SysUserRole::getTenantId, x.getId()));
                    SysUser sysUser = sysUserService.getById(sysUserRole.getUserId());

                    //查询是否已开通汇付
                    EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectOne(new LambdaQueryWrapper<EnterpriseUserMsg>()
                            .eq(EnterpriseUserMsg::getTenantId, x.getId()));

                    if (Objects.nonNull(enterpriseUserMsg)) {
                        x.setIsOpen("1");
                    } else {
                        x.setIsOpen("2");
                    }

                    x.setAccount(sysUser.getAccount());
                });
                //查询关联的账号
                return new PageResult<>(sysTenantPage);
            } else {
                return new PageResult<>();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    @Override
    public List<SysTenant> list(SysTenantParam sysTenantParam) {

        List<SysUser> sysUser = sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda().eq(SysUser::getAccount, sysTenantParam.getName()));
        if (sysUser == null || sysUser.size() < 1) {
            return new ArrayList<>();
        }
        List<Long> tenantIdList = sysUser.stream().map(SysUser::getTenantId).collect(Collectors.toList());
        QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SysTenant::getStatus, CommonStatusEnum.ENABLE.getCode())
                .eq(StrUtil.isNotBlank(sysTenantParam.getContactMobile()), SysTenant::getContactMobile, sysTenantParam.getContactMobile())
                .eq(StrUtil.isNotBlank(sysTenantParam.getContactName()), SysTenant::getContactName, sysTenantParam.getContactName())
                .in(SysTenant::getId, tenantIdList)
                .orderByDesc(BaseEntity::getCreateTime);

        List<SysTenant> sysTenantList = baseMapper.selectList(queryWrapper);
        return sysTenantList;
    }

    public List<SysTenant> loginList(SysTenantParam sysTenantParam) {
        QueryWrapper<SysTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SysTenant::getStatus, CommonStatusEnum.ENABLE.getCode())
                .orderByDesc(BaseEntity::getCreateTime);

        List<SysTenant> sysTenantList = baseMapper.selectList(queryWrapper);
        List<SysTenant> resultList = new ArrayList<>();
        for (SysTenant sysTenant : sysTenantList) {
            SysTenant newSysTenant = new SysTenant();
            newSysTenant.setId(sysTenant.getId());
            newSysTenant.setName(sysTenant.getName());
            resultList.add(newSysTenant);
        }
        return resultList;
    }

    @Autowired
    private SysMenuSelfMapper sysMenuSelfMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Resource
    private SysEmpService sysEmpService;

    /**
     * 添加租户、企业用户基本信息开户、用户业务入驻
     */
    @Override
    public ResponseData add(SysTenantAddParam sysTenantParam) {
        //参数校验
        if (Objects.isNull(sysTenantParam)) {
            return ResponseData.error("参数非法！");
        }


        try {
            SysTenant sysTenant = new SysTenant();
            BeanUtil.copyProperties(sysTenantParam, sysTenant);
            sysTenant.setCreateStatus(1);
            save(sysTenant);

            //判断是否入驻汇付
            String isSettleIn = sysTenantParam.getIsSettleIn();

            //如果入驻才进行如下逻辑
            if ("1".equals(isSettleIn)) {

                //对参数校验，校验成功返回ture，反之false
                boolean b = checkParam(sysTenantParam);

                //校验失败直接返回错误提示
                if (!b) {
                    return ResponseData.error("缺少必要信息！");
                }

                //进行企业用户基本信息开户并进行业务入驻
                accountOpeningAndSettlement(sysTenant, sysTenantParam);
            }

            //添加一个租户管理员账户

            SysUser sysUser = new SysUser();
            sysUser.setStatus(CommonStatusEnum.ENABLE.getCode());
            sysUser.setNickName(sysTenantParam.getName());
            sysUser.setName(sysTenantParam.getName());
            sysUser.setAdminType(AdminTypeEnum.NONE.getCode());
            sysUser.setPhone(sysTenant.getContactMobile());
            sysUser.setAccount(sysTenantParam.getAccount());
            sysUser.setTenantId(sysTenant.getId());
            sysUser.setPassword(MD5Ry.md5(sysTenantParam.getPassword()));

            sysUserService.save(sysUser);

            //创建角色
            SysRole sysRole = new SysRole();
            sysRole.setTenantId(sysTenant.getId());
            sysRole.setCode(RoleConstant.tenant_admin);
            sysRole.setDataScopeType(DataScopeTypeEnum.ALL.getCode());
            sysRole.setName("租戶管理员");
            sysRole.setStatus(CommonStatusEnum.ENABLE.getCode());
            sysRole.setRemark(sysRole.getName());
            sysRoleService.save(sysRole);

            //绑定角色
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(sysRole.getId());
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setTenantId(sysTenant.getId());
            sysUserRoleService.save(sysUserRole);

            //授权菜单
            SysRoleParam sysRoleParam = new SysRoleParam();
            sysRoleParam.setId(sysRole.getId());
            //查询自定义授权表获取菜单id
            List<Long> menuIdList = getMenuIdListByType(1);
            sysRoleParam.setGrantMenuIdList(menuIdList);
            sysRoleParam.setTenantId(sysTenant.getId());
            sysRoleMenuService.grantMenuTenantId(sysRoleParam);

            //添加默认部门对应角色，以及给角色绑定菜单，最后将所有角色id返回
            Map<String, Long> roleIdMap = addRoleAndBindMenu(sysTenant.getId());

            //新增五个固定部门
            createDeptAndBindRole(sysTenant.getId(), roleIdMap);

            //创建租户字典表数据 同步平台数据
//            List<SysDictType> list = dictTypeService.list(new QueryWrapper<SysDictType>().lambda().eq(SysDictType::getTenantId, 1));
//            for (SysDictType dictType : list) {
//                List<SysDictData> dictDataList = dictDataService.list(new QueryWrapper<SysDictData>().lambda()
//                        .eq(SysDictData::getTypeId, dictType.getId()));
//                dictType.setId(null);
//                dictType.setTenantId(sysTenant.getId());
//                dictTypeService.save(dictType);
//                for (SysDictData dictDate : dictDataList) {
//                    dictDate.setTypeId(dictType.getId());
//                    dictDate.setId(null);
//                    dictDate.setTenantId(sysTenant.getId());
//                }
//                dictDataService.saveBatch(dictDataList);
//            }

            //同步角色
//            List<SysRole> sysRoleList = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getTenantId, 1).eq(SysRole::getIsSync, 2));
//            Map<Long, Long> roleMap = new HashMap<>();
//            List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
//            for (SysRole sysrole : sysRoleList) {
//                Long oldRoleId = sysrole.getId();
//                List<Long> roleMenuIdList = sysRoleMenuService.getRoleMenuId(sysrole);
//                sysrole.setId(null);
//                sysrole.setTenantId(sysTenant.getId());
//                sysRoleService.save(sysrole);
//                roleMap.put(oldRoleId, sysrole.getId());
//                //角色菜单
//                for (Long menuId : roleMenuIdList) {
//                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
//                    sysRoleMenu.setRoleId(sysrole.getId());
//                    sysRoleMenu.setMenuId(menuId);
//                    sysRoleMenu.setTenantId(sysTenant.getId());
//                    sysRoleMenuList.add(sysRoleMenu);
//                }
//            }
//            sysRoleMenuService.saveBatch(sysRoleMenuList);

            //菜单 sys_role_menu 同步
//            List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.getBaseMapper().selectList(new QueryWrapper<SysRoleMenu>().lambda().eq(SysRoleMenu::getTenantId, 1));
//            for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
//                sysRoleMenu.setId(null);
//                sysRoleMenu.setTenantId(sysTenant.getId());
//            }
//            sysRoleMenuService.saveBatch(sysRoleMenus);

            //部门 sys_org 同步
//        List<SysOrg> sysOrgs = sysOrgService.getBaseMapper().selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getTenantId, 1).eq(SysOrg::getStatus, 0));
//        List<SysOrg> newSysOrgs = new ArrayList<>();
        //第一个值为原id 第二个值为修改后的id
//        Map<Long, Long> orgMap = new HashMap<>();
//        for (SysOrg sysOrg : sysOrgs) {
//            Long oldId = sysOrg.getId();
//            sysOrg.setId(null);
//            sysOrg.setTenantId(sysTenant.getId());
//            sysOrgService.save(sysOrg);
//            orgMap.put(oldId, sysOrg.getId());
//            newSysOrgs.add(sysOrg);
//        }
        //修改部门pid
//        for (SysOrg sysOrg : newSysOrgs) {
//
//            if (roleMap.get(sysOrg.getRoleId()) != null) {
//                sysOrg.setRoleId(orgMap.get(sysOrg.getRoleId()));
//            }
//            if (orgMap.get(sysOrg.getPid()) != null) {
//                sysOrg.setPid(orgMap.get(sysOrg.getPid()));
//            }
            //修改部门pids
//            StringBuilder pidsString = new StringBuilder();
//            String pids = sysOrg.getPids();
//            if (StringUtils.isNotEmpty(pids)) {
//                String[] split = pids.split(",");
//                for (String oldId : split) {
                    //获取id
//                    String replace = oldId.replace("[", "").replace("]", "");
//                    try {
                        //获取新id
//                        Long aLong = orgMap.get(Long.valueOf(replace));
//                        if (aLong != null) {
//                            pidsString.append("[").append(aLong).append("]").append(",");
//                        } else {
//                            pidsString.append(oldId).append(",");
//                        }
//                    } catch (Exception exception) {
//                        pidsString.append(oldId).append(",");
//                    }
//                }
//                sysOrg.setPids(pidsString.toString());
//            }
//
//
//        }
//        sysOrgService.updateBatchById(sysOrgs);

        //网点 sys_site 同步

//        List<SysSiteAdmin> sysSites = sysSiteAdminService.getBaseMapper().selectList(new QueryWrapper<SysSiteAdmin>().lambda().eq(SysSiteAdmin::getTenantId, 1).eq(SysSiteAdmin::getHasDelete, 0));
//        for (SysSiteAdmin sysSite : sysSites) {
//            sysSite.setId(null);
//            if (orgMap.get(sysSite.getOrgId()) != null) {
//                sysSite.setOrgId(orgMap.get(sysSite.getOrgId()));
//            }
//
//
//            sysSite.setTenantId(sysTenant.getId());
//        }
//        sysSiteAdminService.saveBatch(sysSites);

            //创建一个角色，绑定固定菜单




            //使用异步方法同步平台数据
            sysTenantAsynDataService.asynPlatformData(sysTenant.getId());

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(500,"该租户名称或账号已存在");
        }
        return ResponseData.success(200, "正在创建租户，需要等待1-3分钟", null);
    }

    /**
     * 根据菜单类型获取所有菜单id
     * 1-租户管理员菜单 2-财务部角色菜单 3-业务部角色菜单 4-网点部角色菜单 5-管理部门角色菜单 6-在途人员角色菜单
     * @return
     */
    private List<Long> getMenuIdListByType(Integer menuType) {
        List<SysMenuSelf> sysMenuSelfList = sysMenuSelfMapper.selectList(new LambdaQueryWrapper<SysMenuSelf>()
                .eq(SysMenuSelf::getMenuType, menuType));
        return sysMenuSelfList.stream().map(SysMenuSelf::getMenuId).collect(Collectors.toList());
    }

    /**
     * 添加默认部门对应角色，以及给角色绑定菜单，最后将所有角色id返回
     * @param tenantId
     * @return
     */
    private Map<String, Long> addRoleAndBindMenu(Long tenantId) {
        //创建集合保存所有角色集合
        List<SysRole> roleList = new ArrayList<>();

        //管理角色
        SysRole manageSysRole = new SysRole();
        manageSysRole.setTenantId(tenantId);
        manageSysRole.setCode(RoleConstant.管理部门角色);
        manageSysRole.setName("管理部");
        manageSysRole.setRemark(manageSysRole.getName());
        roleList.add(manageSysRole);

        //在途人员角色
        SysRole personnelInTransitSysRole = new SysRole();
        personnelInTransitSysRole.setTenantId(tenantId);
        personnelInTransitSysRole.setCode(RoleConstant.在途人员角色);
        personnelInTransitSysRole.setName("在途人员");
        personnelInTransitSysRole.setRemark(personnelInTransitSysRole.getName());
        roleList.add(personnelInTransitSysRole);

        //财务部角色
        SysRole financeDepartmentSysRole = new SysRole();
        financeDepartmentSysRole.setTenantId(tenantId);
        financeDepartmentSysRole.setCode(RoleConstant.财务部角色);
        financeDepartmentSysRole.setName("财务部角色");
        financeDepartmentSysRole.setRemark(financeDepartmentSysRole.getName());
        roleList.add(financeDepartmentSysRole);

        //业务部角色
        SysRole businessDepartmentSysRole = new SysRole();
        businessDepartmentSysRole.setTenantId(tenantId);
        businessDepartmentSysRole.setCode(RoleConstant.业务部角色);
        businessDepartmentSysRole.setName("业务部角色");
        businessDepartmentSysRole.setRemark(businessDepartmentSysRole.getName());
        roleList.add(businessDepartmentSysRole);

        //网点部角色
        SysRole branchDepartmentSysRole = new SysRole();
        branchDepartmentSysRole.setTenantId(tenantId);
        branchDepartmentSysRole.setCode(RoleConstant.网点部角色);
        branchDepartmentSysRole.setName("网点部角色");
        branchDepartmentSysRole.setRemark(branchDepartmentSysRole.getName());
        roleList.add(branchDepartmentSysRole);

        //批量新增
        sysRoleService.saveBatch(roleList);

        //管理角色与菜单绑定
        SysRoleParam manageSysRoleParam = new SysRoleParam();
        manageSysRoleParam.setId(manageSysRole.getId());
        manageSysRoleParam.setGrantMenuIdList(getMenuIdListByType(5));
        manageSysRoleParam.setTenantId(tenantId);
        sysRoleMenuService.grantMenuTenantId(manageSysRoleParam);

        //在途人员角色与菜单绑定
        SysRoleParam personnelInTransitSysRoleParam = new SysRoleParam();
        personnelInTransitSysRoleParam.setId(personnelInTransitSysRole.getId());
        personnelInTransitSysRoleParam.setGrantMenuIdList(getMenuIdListByType(6));
        personnelInTransitSysRoleParam.setTenantId(tenantId);
        sysRoleMenuService.grantMenuTenantId(personnelInTransitSysRoleParam);

        //财务部角色与菜单绑定
        SysRoleParam financeDepartmentSysRoleParam = new SysRoleParam();
        financeDepartmentSysRoleParam.setId(financeDepartmentSysRole.getId());
        financeDepartmentSysRoleParam.setGrantMenuIdList(getMenuIdListByType(2));
        financeDepartmentSysRoleParam.setTenantId(tenantId);
        sysRoleMenuService.grantMenuTenantId(financeDepartmentSysRoleParam);

        //业务部角色与菜单绑定
        SysRoleParam businessDepartmentSysRoleParam = new SysRoleParam();
        businessDepartmentSysRoleParam.setId(businessDepartmentSysRole.getId());
        businessDepartmentSysRoleParam.setGrantMenuIdList(getMenuIdListByType(3));
        businessDepartmentSysRoleParam.setTenantId(tenantId);
        sysRoleMenuService.grantMenuTenantId(businessDepartmentSysRoleParam);

        //网点部角色与菜单绑定
        SysRoleParam branchDepartmentSysRoleParam = new SysRoleParam();
        branchDepartmentSysRoleParam.setId(branchDepartmentSysRole.getId());
        branchDepartmentSysRoleParam.setGrantMenuIdList(getMenuIdListByType(4));
        branchDepartmentSysRoleParam.setTenantId(tenantId);
        sysRoleMenuService.grantMenuTenantId(branchDepartmentSysRoleParam);

        //获取角色id并返回
        Map<String, Long> roleIdMap = new HashMap<>();
        roleIdMap.put(RoleConstant.管理部门角色, manageSysRole.getId());
        roleIdMap.put(RoleConstant.在途人员角色, personnelInTransitSysRole.getId());
        roleIdMap.put(RoleConstant.财务部角色, financeDepartmentSysRole.getId());
        roleIdMap.put(RoleConstant.业务部角色, businessDepartmentSysRole.getId());
        roleIdMap.put(RoleConstant.网点部角色, branchDepartmentSysRole.getId());
        return roleIdMap;
//        //授权菜单
//        //查询需要绑定菜单的id集合
//        List<SysMenu> sysMenuAll = new ArrayList<>(); //用来汇总所有SysMenu对象
//        List<SysMenu> sysMenuListA = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
//                .in(SysMenu::getName, "首页", "通讯录", "订单", "全部订单", "异常订单", "订单详情", "提车", "待处理", "提车记录", "发运", "待发运", "发运记录", "在途", "签收", "待签收", "签收记录", "交付记录", "价格", "价格库", "添加路线价格", "公共管理", "地址库", "轮播图管理", "通知公告")
//                .eq(SysMenu::getStatus, 0));
//        if (CollectionUtil.isNotEmpty(sysMenuListA)) {
//            sysMenuAll.addAll(sysMenuListA);
//        }
//        SysMenu financeSysMenu = sysMenuMapper.selectOne(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getName, "财务").eq(SysMenu::getStatus, 0));
//        if (Objects.nonNull(financeSysMenu)) {
//            sysMenuAll.add(financeSysMenu);
//            List<SysMenu> sysMenuListB = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, financeSysMenu.getId()).eq(SysMenu::getStatus, 0));
//            if (CollectionUtil.isNotEmpty(sysMenuListB)) {
//                sysMenuAll.addAll(sysMenuListB);
//            }
//        }
//        SysMenu noticeSysMenu = sysMenuMapper.selectOne(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getName, "公告管理").eq(SysMenu::getStatus, 0));
//        if (Objects.nonNull(noticeSysMenu)) {
//            sysMenuAll.add(noticeSysMenu);
//            List<SysMenu> sysMenuListC = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, noticeSysMenu.getId()).eq(SysMenu::getStatus, 0));
//            if (CollectionUtil.isNotEmpty(sysMenuListC)) {
//                sysMenuAll.addAll(sysMenuListC);
//            }
//        }
//        //提取SysMenu对象中的主键id为List集合
//        List<Long> sysMenuIdList = sysMenuAll.stream().filter(sysMenu -> !"财务-改单".equals(sysMenu.getName()))
//                .map(SysMenu::getId).collect(Collectors.toList());
    }

    /**
     * 新增三个固定部门
     */
    private void createDeptAndBindRole(Long tenantId, Map<String, Long> roleIdMap) {
        List<SysOrg> sysOrgList = new ArrayList<>();
        SysOrg sysOrg1 = new SysOrg();
        SysOrg sysOrg2 = new SysOrg();
        SysOrg sysOrg3 = new SysOrg();
        SysOrg sysOrg4 = new SysOrg();
        SysOrg sysOrg5 = new SysOrg();

        sysOrg1.setPid(0L);
        sysOrg2.setPid(0L);
        sysOrg3.setPid(0L);
        sysOrg4.setPid(0L);
        sysOrg5.setPid(0L);

        sysOrg1.setPids("[0],");
        sysOrg2.setPids("[0],");
        sysOrg3.setPids("[0],");
        sysOrg4.setPids("[0],");
        sysOrg5.setPids("[0],");

        sysOrg1.setName("财务部");
        sysOrg2.setName("业务部");
        sysOrg3.setName("网点部");
        sysOrg4.setName("管理部门");
        sysOrg5.setName("在途人员");

        //给对应部门绑定角色
        sysOrg1.setRoleId(roleIdMap.get(RoleConstant.财务部角色));
        sysOrg2.setRoleId(roleIdMap.get(RoleConstant.业务部角色));
        sysOrg3.setRoleId(roleIdMap.get(RoleConstant.网点部角色));
        sysOrg4.setRoleId(roleIdMap.get(RoleConstant.管理部门角色));
        sysOrg5.setRoleId(roleIdMap.get(RoleConstant.在途人员角色));

        sysOrg1.setCode("caiwu_dept");
        sysOrg2.setCode("yewu_dept");
        sysOrg3.setCode("wangdian_dept");
        sysOrg4.setCode("manager_dept");
        sysOrg5.setCode("personnel_in_transit_dept");

        sysOrg1.setSort(100);
        sysOrg2.setSort(100);
        sysOrg3.setSort(100);
        sysOrg4.setSort(100);
        sysOrg5.setSort(100);

        sysOrg1.setCreateTime(new Date());
        sysOrg2.setCreateTime(new Date());
        sysOrg3.setCreateTime(new Date());
        sysOrg4.setCreateTime(new Date());
        sysOrg5.setCreateTime(new Date());

        sysOrg1.setUpdateTime(new Date());
        sysOrg2.setUpdateTime(new Date());
        sysOrg3.setUpdateTime(new Date());
        sysOrg4.setUpdateTime(new Date());
        sysOrg5.setUpdateTime(new Date());

        Long id = LoginContextHolder.me().getSysLoginUser().getId();

        sysOrg1.setCreateUser(id);
        sysOrg2.setCreateUser(id);
        sysOrg3.setCreateUser(id);
        sysOrg4.setCreateUser(id);
        sysOrg5.setCreateUser(id);

        sysOrg1.setUpdateUser(id);
        sysOrg2.setUpdateUser(id);
        sysOrg3.setUpdateUser(id);
        sysOrg4.setUpdateUser(id);
        sysOrg5.setUpdateUser(id);

        sysOrg1.setTenantId(tenantId);
        sysOrg2.setTenantId(tenantId);
        sysOrg3.setTenantId(tenantId);
        sysOrg4.setTenantId(tenantId);
        sysOrg5.setTenantId(tenantId);

        sysOrg1.setIsSite(1);
        sysOrg2.setIsSite(1);
        sysOrg3.setIsSite(1);
        sysOrg4.setIsSite(1);
        sysOrg5.setIsSite(1);

        sysOrgList.add(sysOrg1);
        sysOrgList.add(sysOrg2);
        sysOrgList.add(sysOrg3);
        sysOrgList.add(sysOrg4);
        sysOrgList.add(sysOrg5);

        sysOrgService.saveBatch(sysOrgList);
    }

    /**
     * 对参数校验，校验成功返回ture，反之false
     */
    private boolean checkParam(SysTenantAddParam sysTenantParam) {
        //获取内置对象
        EnterpriseUserMsgVO enterpriseUserMsgVO = sysTenantParam.getEnterpriseUserMsgVO();
        UserBusinessSettleMsgVO userBusinessSettleMsgVO = sysTenantParam.getUserBusinessSettleMsgVO();

        //如果有一个对象为null直接返回false
        if (Objects.isNull(enterpriseUserMsgVO) || Objects.isNull(userBusinessSettleMsgVO)) {
            return false;
        }

        //判断对象中的属性是否有值，如果有一个必填属性没值，直接返回false
        if (StringUtils.isBlank(enterpriseUserMsgVO.getRegName()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLicenseCode()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLicenseValidityType()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLicenseBeginDate()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLegalCertBeginDate()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getContactName()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getContactMobile()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getCommission()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getRegProvId()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getRegAreaId()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getRegDistrictId()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getRegDetail()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLegalName()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLegalCertType()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLegalCertNo()) ||
                StringUtils.isBlank(enterpriseUserMsgVO.getLegalCertValidityType()) ||
                Objects.isNull(userBusinessSettleMsgVO.getCardType()) ||
                StringUtils.isBlank(userBusinessSettleMsgVO.getCardName()) ||
                StringUtils.isBlank(userBusinessSettleMsgVO.getCardNo()) ||
                StringUtils.isBlank(userBusinessSettleMsgVO.getProvId()) ||
                StringUtils.isBlank(userBusinessSettleMsgVO.getAreaId())) {
            return false;
        }

        //上面过滤条件通过返回true
        return true;
    }


    /**
     * 开户和入驻
     */
    private void accountOpeningAndSettlement(SysTenant sysTenant, SysTenantAddParam sysTenantParam) {
        //获取当前系统用户id
        Long sysId = new CustomMetaObjectHandler().getUserUniqueId();

        //获取租户id
        Long tenantId = sysTenant.getId();

        //将开户信息入库
        saveAccountOpening(tenantId, sysTenantParam.getEnterpriseUserMsgVO(), sysId);

        //调用三方接口将开户信息上传到汇付
        String huiFuId = doCreateEnterpriseUser(sysTenantParam, tenantId);

        //将入驻信息入库
        saveAccountSettlement(huiFuId, tenantId, sysId, sysTenantParam);

        //调用三方接口入驻到汇付
        doSettleIn(sysTenantParam, tenantId, huiFuId);
    }

    /**
     * 调用三方接口入驻到汇付
     */
    private void doSettleIn(SysTenantAddParam sysTenantParam, Long tenantId, String huiFuId) {
        //创建参数对象
        SettleInParam settleInParam = new SettleInParam();

        //属性拷贝
        BeanUtils.copyProperties(sysTenantParam.getUserBusinessSettleMsgVO(), settleInParam);

        //属性补全
        settleInParam.setHuifuId(huiFuId); //汇付id
        settleInParam.setReqDate(DateTools.getCurrentDateYYYYMMDD()); //请求日期
        settleInParam.setReqSeqId(SequenceTools.getReqSeqId32()); //请求流水号
        settleInParam.setUpperHuifuId(ApiPayConstant.SYS_ID); //渠道商id

        try {
            //调用第三方接口
            Map<String, Object> settleInResult = ApiPayUtil.settleIn(settleInParam);
            //如果入驻失败直接抛出异常
            if (!"00000000".equals(settleInResult.get("resp_code"))) {
                throw new ServiceException(500, (String) settleInResult.get("resp_desc"));
            }
            //入驻成功修改数据库中入驻状态
            UserBusinessSettleMsg userBusinessSettleMsg = userBusinessSettleMsgMapper.selectOne(new LambdaQueryWrapper<UserBusinessSettleMsg>()
                    .eq(UserBusinessSettleMsg::getTenantId, tenantId));
            userBusinessSettleMsg.setStatus(1); //入驻成功
            userBusinessSettleMsg.setReqDate(settleInParam.getReqDate()); //请求日期
            userBusinessSettleMsg.setReqSeqId(settleInParam.getReqSeqId()); //请求流水号

            //执行修改
            userBusinessSettleMsgMapper.updateById(userBusinessSettleMsg);
        } catch (Exception e) {
            e.printStackTrace();
            //调用出错直接抛出异常
            throw new ServiceException(500, e.getMessage());
        }
    }

    /**
     * 将入驻信息入库
     */
    private void saveAccountSettlement(String huiFuId, Long tenantId, Long sysId, SysTenantAddParam sysTenantParam) {
        //创建入驻信息实体类
        UserBusinessSettleMsg userBusinessSettleMsg = new UserBusinessSettleMsg();

        //属性拷贝
        BeanUtils.copyProperties(sysTenantParam.getUserBusinessSettleMsgVO(), userBusinessSettleMsg);

        //属性补全
        userBusinessSettleMsg.setCreateBy(sysId);
        userBusinessSettleMsg.setUpdateBy(sysId);
        userBusinessSettleMsg.setCreateTime(LocalDateTime.now());
        userBusinessSettleMsg.setUpdateTime(LocalDateTime.now());
        userBusinessSettleMsg.setHuifuId(huiFuId);
        userBusinessSettleMsg.setUpperHuifuId(ApiPayConstant.SYS_ID);
        //暂时将入驻状态设置为处理中
        userBusinessSettleMsg.setStatus(0);
        //租户id
        userBusinessSettleMsg.setTenantId(tenantId);

        //执行新增
        userBusinessSettleMsgMapper.insert(userBusinessSettleMsg);
    }

    /**
     * 调用三方接口将开户信息上传到汇付
     */
    private String doCreateEnterpriseUser(SysTenantAddParam sysTenantParam, Long tenantId) {
        //创建传参对象
        EnterpriseUserParam param = new EnterpriseUserParam();

        //进行属性拷贝
        BeanUtils.copyProperties(sysTenantParam.getEnterpriseUserMsgVO(), param);

        //进行属性填充
        param.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        param.setReqSeqId(SequenceTools.getReqSeqId32());
        try {
            //调用第三方接口
            Map<String, Object> openResult = ApiPayUtil.createEnterpriseUser(param);

            //如果返回的结果没有成功，直接抛出异常，并提示错误信息
            if (!"00000000".equals(openResult.get("resp_code"))) {
                throw new ServiceException(500, (String) openResult.get("resp_desc"));
            }

            //如果成功修改进件状态为成功，并将返回的汇付id存入
            //根据租户id查询进件信息
            EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectOne(new LambdaQueryWrapper<EnterpriseUserMsg>()
                    .eq(EnterpriseUserMsg::getTenantId, tenantId));
            enterpriseUserMsg.setStatus(1); //设置状态为成功
            String huifu_id = (String) openResult.get("huifu_id"); //获取汇付id
            enterpriseUserMsg.setHuifuId(huifu_id); //保存汇付id
            enterpriseUserMsg.setReqDate(param.getReqDate()); //请求时间
            enterpriseUserMsg.setReqSeqId(param.getReqSeqId()); //请求流水号
            //执行修改
            enterpriseUserMsgMapper.updateById(enterpriseUserMsg);

            //返回
            return huifu_id;
        } catch (Exception e) {
            e.printStackTrace();
            //如果调用报错直接抛出异常，并提示异常信息
            throw new ServiceException(500, e.getMessage());
        }
    }

    /**
     * 开户信息入库
     */
    private void saveAccountOpening(Long tenantId, EnterpriseUserMsgVO enterpriseUserMsgVO, Long sysId) {
        //创建开户信息表实体类对象
        EnterpriseUserMsg enterpriseUserMsg = new EnterpriseUserMsg();

        //进行属性拷贝
        BeanUtils.copyProperties(enterpriseUserMsgVO, enterpriseUserMsg);

        //补全属性
        enterpriseUserMsg.setCreateBy(sysId);
        enterpriseUserMsg.setUpdateBy(sysId);
        enterpriseUserMsg.setCreateTime(LocalDateTime.now());
        enterpriseUserMsg.setUpdateTime(LocalDateTime.now());
        //暂时将开户状态设置为处理中
        enterpriseUserMsg.setStatus(0);
        //租户Id
        enterpriseUserMsg.setTenantId(tenantId);
        //证件类型
        enterpriseUserMsg.setLicenseValidityType(Integer.valueOf(enterpriseUserMsgVO.getLicenseValidityType()));
        enterpriseUserMsg.setLegalCertValidityType(Integer.valueOf(enterpriseUserMsgVO.getLegalCertValidityType()));

        //执行新增
        enterpriseUserMsgMapper.insert(enterpriseUserMsg);
    }


    @Autowired
    private SysRoleMenuService sysRoleMenuService;


    @Override
    public void edit(SysTenantEditParam sysTenantParam) {

        SysTenant sysTenant = new SysTenant();
        BeanUtil.copyProperties(sysTenantParam, sysTenant);
        updateById(sysTenant);

        //添加一个租户管理员账户
        //判断账号是否重复
        Integer count = sysUserMapper.selectCount(new QueryWrapper<SysUser>().lambda().
                eq(SysUser::getAccount, sysTenantParam.getAccount())
                .eq(SysUser::getTenantId, sysTenant.getId())
                .ne(SysUser::getId, sysTenantParam.getId())
                .ne(SysUser::getStatus, CommonStatusEnum.DELETED));
        if (count > 0) {
            throw new PermissionException(PermissionExceptionEnum.ACCOUNT_REPEAT);
        }

        //修改账号和密码
        Long tenantAdminId = sysRoleService.getRoleIdByNameAndTenantId(RoleConstant.tenant_admin, sysTenantParam.getId());
        SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, tenantAdminId)
                .eq(SysUserRole::getTenantId, sysTenantParam.getId()));
        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserRole.getUserId());
        sysUser.setStatus(CommonStatusEnum.ENABLE.getCode());
        sysUser.setNickName(sysTenantParam.getName());
        sysUser.setName(sysTenantParam.getName());
        sysUser.setAdminType(AdminTypeEnum.NONE.getCode());
        sysUser.setAccount(sysTenant.getAccount());
        sysUser.setPhone(sysTenant.getContactMobile());
        sysUser.setTenantId(sysTenant.getId());
        //sysUser.setPassword(MD5Ry.md5(sysTenantParam.getPassword()));

        sysUserService.updateById(sysUser);
    }

    /**
     * 如果手续费不为空则进行修改
     */
    private void updateCommission(String commission, Long id) {
        //判断手续费是否为空
        if (StringUtils.isBlank(commission)) {
            return;
        }

        //现根据租户id去查询数据库
        EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectById(id);

        //进行安全校验
        if (Objects.isNull(enterpriseUserMsg)) {
            return;
        }

        //修改手续费属性并更新数据库
        enterpriseUserMsg.setCommission(commission);
        enterpriseUserMsgMapper.updateById(enterpriseUserMsg);
    }

    @Override
    public void checkTenantDataPermission(Long tenantId) {
        //租户和总平台的数据不可共通
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (tenantId != null && sysLoginUser.getTenantId() == null) {
            throw new CustomException("系统不可删除租户的数据");
        }
        if (tenantId == null && sysLoginUser.getTenantId() != 1l) {
            throw new CustomException("租户不可删除总平台的数据");
        }

    }

    @Override
    public void changeStatus(SysTenantParam sysTenantParam) {
        Integer status = sysTenantParam.getStatus();
        //校验状态在不在枚举值里
        CommonStatusEnum.validateStatus(status);

        //更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<SysTenant> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysTenant::getId, sysTenantParam.getId())
                .and(i -> i.ne(SysTenant::getStatus, CommonStatusEnum.DELETED.getCode()))
                .set(SysTenant::getStatus, status);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }
    }

    @Override
    public void grantMenu(SysTenantEditParam sysTenantParam) {
        //查询当前租户的租户管理员角色ID
        SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getTenantId, sysTenantParam.getId())
                .eq(SysRole::getCode, RoleConstant.tenant_admin));
        SysRoleParam sysRoleParam = new SysRoleParam();
        sysRoleParam.setId(sysRole.getId());
        sysRoleParam.setGrantMenuIdList(sysTenantParam.getGrantMenuIdList());
        sysRoleParam.setTenantId(sysTenantParam.getId());

        sysRoleMenuService.grantMenuTenantId(sysRoleParam);
    }

    @Override
    public ResponseData detail(SysTenantEditParam sysTenantParam) {
        SysTenant sysTenant = getById(sysTenantParam.getId());
        //修改账号和密码
        Long tenantAdminId = sysRoleService.getRoleIdByNameAndTenantId(RoleConstant.tenant_admin, sysTenantParam.getId());
        SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, tenantAdminId)
                .eq(SysUserRole::getTenantId, sysTenantParam.getId()));

        SysUser sysUser = sysUserService.getById(sysUserRole.getUserId());
        List<Long> roleIdList = new ArrayList<>();
        roleIdList.add(sysUserRole.getRoleId());
        List<Long> roleMenuIdList = sysRoleMenuService.getRoleMenuIdList(roleIdList, sysUser.getId());
        sysTenant.setRoleMenuIdList(roleMenuIdList);
        sysTenant.setAccount(sysUser.getAccount());
        return ResponseData.success(sysTenant);
    }

    @Override
    public void resetPasswords(SysTenantEditParam sysTenantParam) {
        //修改账号和密码
        Long tenantAdminId = sysRoleService.getRoleIdByNameAndTenantId(RoleConstant.tenant_admin, sysTenantParam.getId());
        SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, tenantAdminId)
                .eq(SysUserRole::getTenantId, sysTenantParam.getId()));

        SysUser sysUser = sysUserService.getById(sysUserRole.getUserId());
        SysUser newUser = new SysUser();
        newUser.setId(sysUser.getId());
        newUser.setPassword(MD5Ry.md5("123456"));
    }

    @Override
    public void editStatus(SysTenantEditParam sysTenantParam) {
        SysTenant sysTenant = new SysTenant();
        sysTenant.setId(sysTenantParam.getId());
        sysTenant.setStatus(sysTenantParam.getStatus());
        this.updateById(sysTenant);
    }

    /**
     * 根据租户id查询入驻汇付信息
     */
    @Override
    public ResponseData<GetHuifuMsgDTO> getHuifuMsg(GetHuifuMsgVO getHuifuMsgVO) {
        //获取参数租户Id
        Long tenantId = Long.valueOf(getHuifuMsgVO.getTenantId());

        //根据租户id查询汇付开户信息
        EnterpriseUserMsg enterpriseUserMsg = enterpriseUserMsgMapper.selectOne(new LambdaQueryWrapper<EnterpriseUserMsg>()
                .eq(EnterpriseUserMsg::getTenantId, tenantId));

        //根据租户id查询汇付业务入驻信息
        UserBusinessSettleMsg userBusinessSettleMsg = userBusinessSettleMsgMapper.selectOne(new LambdaQueryWrapper<UserBusinessSettleMsg>()
                .eq(UserBusinessSettleMsg::getTenantId, tenantId));

        //如果查询的信息有为空直接响应空数据
        if (Objects.isNull(enterpriseUserMsg)) {
            return ResponseData.success();
        }

        //创建GetHuifuMsgDTO对象
        GetHuifuMsgDTO getHuifuMsgDTO = new GetHuifuMsgDTO();

        //如果不为空直接将信息拷贝到GetHuifuMsgDTO对象中
        BeanUtils.copyProperties(enterpriseUserMsg, getHuifuMsgDTO);
        getHuifuMsgDTO.setLicenseValidityType(enterpriseUserMsg.getLicenseValidityType() + "");
        getHuifuMsgDTO.setLegalCertValidityType(enterpriseUserMsg.getLegalCertValidityType() + "");
        getHuifuMsgDTO.setMsgId(enterpriseUserMsg.getId());
        BeanUtils.copyProperties(userBusinessSettleMsg, getHuifuMsgDTO);

        //将一些编码属性查询对应名称并赋值
        setOtherValue(getHuifuMsgDTO);

        //返回结果
        return ResponseData.success(getHuifuMsgDTO);
    }

    /**
     * 将一些编码属性查询对应名称并赋值
     */
    private void setOtherValue(GetHuifuMsgDTO getHuifuMsgDTO) {
        //查询注册地址中省市区名
        List<ProvincialAndUrbanCode> registerAddrList = provincialAndUrbanCodeMapper.selectList(new LambdaQueryWrapper<ProvincialAndUrbanCode>()
                .eq(ProvincialAndUrbanCode::getType, 1)
                .eq(ProvincialAndUrbanCode::getCode, getHuifuMsgDTO.getRegProvId())
                .or()
                .eq(ProvincialAndUrbanCode::getType, 2)
                .eq(ProvincialAndUrbanCode::getCode, getHuifuMsgDTO.getRegAreaId())
                .or()
                .eq(ProvincialAndUrbanCode::getType, 3)
                .eq(ProvincialAndUrbanCode::getCode, getHuifuMsgDTO.getRegDistrictId()));

        //校验后遍历集合
        if (Objects.nonNull(registerAddrList) && registerAddrList.size() > 0) {

            registerAddrList.forEach(s -> {
                Integer type = s.getType();

                //省
                if (type == 1) {
                    getHuifuMsgDTO.setRegProvName(s.getName());
                }

                //市
                if (type == 2) {
                    getHuifuMsgDTO.setRegAreaName(s.getName());
                }

                //区
                if (type == 3) {
                    getHuifuMsgDTO.setRegDistrictName(s.getName());
                }
            });

        }

        //查询银行所在省市
        List<ProvincialAndUrbanCode> bankAddrList = provincialAndUrbanCodeMapper.selectList(new LambdaQueryWrapper<ProvincialAndUrbanCode>()
                .eq(ProvincialAndUrbanCode::getType, 1)
                .eq(ProvincialAndUrbanCode::getCode, getHuifuMsgDTO.getProvId())
                .or()
                .eq(ProvincialAndUrbanCode::getType, 2)
                .eq(ProvincialAndUrbanCode::getCode, getHuifuMsgDTO.getAreaId()));

        //校验后遍历集合
        if (Objects.nonNull(bankAddrList) && bankAddrList.size() > 0) {

            bankAddrList.forEach(s -> {
                Integer type = s.getType();

                //省
                if (type == 1) {
                    getHuifuMsgDTO.setProvName(s.getName());
                }

                //市
                if (type == 2) {
                    getHuifuMsgDTO.setAreaName(s.getName());
                }

            });

        }

        //查询银行编码对应的银行名
        BankCode bankCode = bankCodeMapper.selectOne(new LambdaQueryWrapper<BankCode>()
                .eq(BankCode::getBankCode, getHuifuMsgDTO.getBankCode()));

        //校验后赋值
        if (Objects.nonNull(bankCode)) {
            getHuifuMsgDTO.setBankName(bankCode.getBankName());
        }

        //查询法人证件类型名
        DocumentTypeCode documentTypeCode = documentTypeCodeMapper.selectOne(new LambdaQueryWrapper<DocumentTypeCode>()
                .eq(DocumentTypeCode::getCode, getHuifuMsgDTO.getLegalCertType()));

        //校验后赋值
        if (Objects.nonNull(documentTypeCode)) {
            getHuifuMsgDTO.setLegalCertTypeName(documentTypeCode.getType());
        }
    }

    /**
     * 入驻汇付或者修改手续费
     */
    @Override
    public ResponseData settleOrUpdateCommission(SettleOrUpdateCommissionVO settleOrUpdateCommissionVO) {
        //判断企业用户开户基本信息id
        Long id = settleOrUpdateCommissionVO.getEnterpriseUserMsgVO().getId();

        //如果id不为空则修改手续费
        if (Objects.nonNull(id)) {
            updateCommission(settleOrUpdateCommissionVO.getEnterpriseUserMsgVO().getCommission(), id);
        } else {
            //如果id为空则入驻汇付
            SysTenant sysTenant = new SysTenant();
            //设置租户id
            sysTenant.setId(Long.valueOf(settleOrUpdateCommissionVO.getEnterpriseUserMsgVO().getTenantId()));

            SysTenantAddParam sysTenantParam = new SysTenantAddParam();
            sysTenantParam.setEnterpriseUserMsgVO(settleOrUpdateCommissionVO.getEnterpriseUserMsgVO());
            sysTenantParam.setUserBusinessSettleMsgVO(settleOrUpdateCommissionVO.getUserBusinessSettleMsgVO());

            accountOpeningAndSettlement(sysTenant, sysTenantParam);
        }

        //返回成功
        return ResponseData.success();
    }

}
